<template>
  <main class="apply-dls-wrapper">
    <!-- 头部背景 -->
    <div class="apply_headimg">
      <div class="reference" v-if="other_config.recommend_nickname && other_config.recommend_headimg && other_config.dhsRank">
        <img :src="other_config.recommend_headimg">
        <div>来自{{other_config.recommend_nickname}}的推荐</div>
      </div>
      <img :src="other_config.topRequsetBg" alt />
    </div>
    <section class="apply_tip">
        欢迎加入
        <span>{{other_config.apply_tip_title }}</span>，请填写申请信息！
      </section>
    <div class="apply_wrapper">

      <div class="addurl_con">
        <ul>
          <li
            v-if="is_mmxx"
            class="clearfix"
          >
            <label>
              <b class="colorRed">*</b>
              推荐人ID
            </label>
            <div class="w60 fr">
              <input
                placeholder="请填写上级ID"
                v-model="apply_user_id"
                class="textw"
                @blur="blurEvent()"
              />
            </div>
          </li>

          <!-- 加盟方式 -->
          <li class="clearfix">
            <label>
              <b class="colorRed">*</b>加盟方式
            </label>
            <div class="w60 fr">
              <van-radio-group v-model="apply_level">
                <div class="fl radioChange">
                  <van-radio
                    @click="selectApplyLevel(1)"
                    v-show="dls.display == 1"
                    name="1"
                    icon-size="16px"
                  >{{ dls.ftitle_agencies }}</van-radio>
                </div>
                <div class="fl radioChange">
                  <van-radio
                    @click="selectApplyLevel(2)"
                    v-show="dhs.display == 1"
                    name="2"
                    icon-size="16px"
                  >{{ dhs.ftitle_agencies }}</van-radio>
                </div>
              </van-radio-group>
            </div>
          </li>
          <!-- 代理商订货商级别 -->
          <li v-show="dls.checked" class="clearfix apply_level apply_level_dls">
            <label>
              <b class="colorRed">*</b>{{ dls.ftitle_agencies }}级别
            </label>
            <div class="w60 fr">
              <div class="apply-right" @click="showDlsPicker=true"><span :class="showDlsName ? 'col9':''">{{showDlsName ? showDlsName:dls.text}}</span><img src="https://img.wifenxiao.com/h5-wfx/images/refund/arrow_r.png" alt=""></div>
            </div>
          </li>
          <li v-show="dhs.checked" class="clearfix apply_level apply_level_dhs">
            <label>
              <b class="colorRed">*</b>{{ dhs.ftitle_agencies }}级别
            </label>
            <div class="w60 fr">
              <div class="apply-right" v-if="other_config.dhsRank && dhsRank" ><span>{{showDhsName ? showDhsName:dhs.text}}</span></div>
              <div class="apply-right" v-else @click="showDhsPicker=true"><span :class="showDhsName ? 'col9':''">{{showDhsName ? showDhsName:dhs.text}}</span><img src="https://img.wifenxiao.com/h5-wfx/images/refund/arrow_r.png" alt=""></div>
            </div>
          </li>
          <!--  浙江集乘网络科技 定制 start   -->
          <li class="clearfix" v-if="company_head.display == 1">
            <label>
              <b class="colorRed" v-if="company_head.must == 1">*</b>
              {{company_head.name}}
            </label>
            <div class="w60 fr">
              <input
                      :placeholder="'请填写' + company_head.name"
                      v-model="company_head.value"
                      class="textw"
                      @blur="blurEvent()"
                      maxlength="20"
              />
            </div>
          </li>
          <li class="clearfix" v-if="company_taxNumber.display == 1">
            <label>
              <b class="colorRed" v-if="company_taxNumber.must == 1">*</b>
              {{company_taxNumber.name}}
            </label>
            <div class="w60 fr">
              <input
                      :placeholder="'请填写'+ company_taxNumber.name"
                      v-model="company_taxNumber.value"
                      class="textw"
                      @blur="blurEvent()"
                      maxlength="30"
              />
            </div>
          </li>
          <!--    浙江集乘网络科技 定制 end    -->
          <!-- 申请类型 -->
          <li v-if="other_config.need_apply_type == 1" class="clearfix">
            <label>
              <b class="colorRed">*</b>类型
            </label>
            <div class="w60 fr">
              <van-radio-group v-model="other_config.applyType">
                <div class="fl radioChange">
                  <van-radio name="2" icon-size="16px">企业</van-radio>
                </div>
                <div class="fl radioChange">
                  <van-radio name="1" icon-size="16px">个人</van-radio>
                </div>
              </van-radio-group>
            </div>
          </li>
          <!-- 公司名称-->
          <li
            v-if="other_config.need_apply_type==1 && company_name.display==1"
            v-show="other_config.applyType==2"
            class="clearfix"
          >
            <label>
              <b v-if="company_name.must==1" class="colorRed">*</b>
              {{company_name.name}}
            </label>
            <div class="w60 fr">
              <input
                :placeholder="'请填写'+company_name.name"
                v-model="company_name.value"
                class="textw"
                @blur="blurEvent()"
              />
            </div>
          </li>
          <!-- 营业执照号-->
          <li
            v-if="other_config.need_apply_type==1 && business_licence_num.display==1"
            v-show="other_config.applyType==2"
            class="clearfix"
            @blur="blurEvent()"
          >
            <label>
              <b v-if="business_licence_num.must==1" class="colorRed">*</b>
              {{business_licence_num.name}}
            </label>
            <div class="w60 fr">
              <input
                :placeholder="'请填写'+business_licence_num.name"
                v-model="business_licence_num.value"
                class="textw"
              />
            </div>
          </li>
          <!-- 上传营业执照-->
          <li
            v-if="other_config.need_apply_type==1 && business_licence_img.display==1"
            v-show="other_config.applyType==2"
            class="clearfix autoHeight"
          >
            <label>
              <b v-if="business_licence_img.must==1" class="colorRed">*</b>
              {{business_licence_img.name}}
            </label>
            <div class="w60 fr">
              <!-- TODO 上传营业执照 -->
              <SmallUploadImg ref="smallUploadImgYYZZ" :maxLength="5"></SmallUploadImg>
            </div>
          </li>
          <!-- 身份证号-->
          <li v-if="other_config.need_apply_type==1 && card_num.display==1" class="clearfix">
            <label>
              <b v-if="card_num.must==1" class="colorRed">*</b>
              {{card_num.name}}
            </label>
            <div class="w60 fr">
              <input
                :placeholder="'请填写'+card_num.name"
                v-model="card_num.value"
                class="textw"
                @blur="blurEvent()"
              />
            </div>
          </li>
          <!-- 上传身份证-->
          <li v-if="other_config.need_apply_type==1 && card_img.display==1" class="clearfix autoHeight">
            <label>
              <b v-if="card_img.must==1" class="colorRed">*</b>
              {{card_img.name}}
            </label>
            <div class="w60 fr">
              <!-- TODO 上传身份证 -->
              <SmallUploadImg ref="smallUploadImgCardPos" :maxLength="1"></SmallUploadImg>

              <span v-if="card_txt">{{ card_txt }}</span>
            </div>
          </li>
          <!-- 性别 -->
          <li v-if="other_config.need_apply_type==1 && sex.display==1" class="clearfix">
            <label>
              <b v-if="sex.must==1" class="colorRed">*</b>
              {{sex.name}}
            </label>
            <div class="w60 fr">
              <van-radio-group v-model="sex.value">
                <div class="fl radioChange">
                  <van-radio name="1" icon-size="16px">男</van-radio>
                </div>
                <div class="fl radioChange">
                  <van-radio name="2" icon-size="16px">女</van-radio>
                </div>
                <div class="fl radioChange">
                  <van-radio name="3" icon-size="16px">保密</van-radio>
                </div>
              </van-radio-group>
            </div>
          </li>
          <!-- 申请人-->
          <li v-if="agent_name.display==1" class="clearfix">
            <label>
              <b v-if="agent_name.must==1" class="colorRed">*</b>
              {{agent_name.name}}
            </label>
            <div class="w60 fr">
              <input
                placeholder="请输入您的真实姓名"
                v-model="agent_name.value"
                class="textw"
                @blur="blurEvent()"
              />
            </div>
          </li>
          <!-- 联系人电话-->
          <li v-if="apply_mobile.display==1" class="clearfix">
            <label>
              <b v-if="apply_mobile.must==1" class="colorRed">*</b>
              {{apply_mobile.name}}
            </label>
            <div class="w60 fr">
              <input
                placeholder="请输入您的手机号码"
                v-model="apply_mobile.value"
                class="textw"
                @blur="blurEvent()"
              />
            </div>
          </li>
          <!-- 微信号-->
          <li v-if="apply_weixin.display==1" class="clearfix">
            <label>
              <b v-if="apply_weixin.must==1" class="colorRed">*</b>
              {{apply_weixin.name}}
            </label>
            <div class="w60 fr">
              <input
                :placeholder="'请填写'+apply_weixin.name"
                v-model="apply_weixin.value"
                class="textw"
                @blur="blurEvent()"
              />
            </div>
          </li>
          <!-- 验证码-->
          <li
            class="clearfix list-item"
            style="position:relative"
            v-if="other_config.check_apply_mobile == 1 && apply_mobile.display == 1"
          >
            <label>
              <b class="colorRed">*</b>验证码
            </label>
            <div class="w60 fr">
              <input
                type="text"
                placeholder="填写验证码"
                class="textw textw_code fl"
                v-model="apply_mobile.code"
                @blur="blurEvent()"
                @focus="focusEvent"
              />
              <img
                :src="verifyImg"
                class="verify-img"
                @click="refreshVerify"
              />
            </div>
          </li>
          <!-- 短信验证码-->
          <li
            v-if="other_config.check_apply_mobile == 1 && apply_mobile.display == 1"
            class="clearfix"
            style="position:relative"
          >
            <label>
              <b class="colorRed">*</b>短信验证码
            </label>
            <div class="w60 fr">
              <input
                placeholder="填写短信验证码"
                v-model="apply_mobile.vcode"
                class="textw textw_code fl"
                style="width: 50%"
                @blur="blurEvent()"
              />
              <button
                class="setpwd_but"
                @click="refreshmsgVerify"
                :disabled="!other_config.canSendMsg"
              >{{other_config.sendMsgBtnTxt}}</button>
            </div>
          </li>
          <!-- 地址信息-->
          <li v-if="apply_address.display==1" class="clearfix">
            <label>
              <b v-show="apply_address.must==1" class="colorRed">*</b>
              {{apply_address.name}}：
            </label>
            <div class="w60 fr">
              <small-area-picker class="area-picker" @procityareaInfo="procityareaInfo"></small-area-picker>
            </div>

          </li>
          <!-- 详细地址-->
          <li v-if="apply_address.display==1" class="clearfix">
            <label>
              <b v-if="apply_address.must==1" class="colorRed">*</b>
              详细地址
            </label>
            <div class="w60 fr">
              <input
                placeholder="请输入您的详细地址"
                v-model="address.value"
                class="textw"
                maxlength="225"
                @blur="blurEvent()" />
            </div>
          </li>
          <!--上传资质-->
          <li
            v-if="apply_qualifications.display==1"
            class="clearfix autoHeight"
          >
            <label>
              <b v-if="apply_qualifications.must==1" class="colorRed">*</b>
              {{apply_qualifications.name}}
            </label>
            <div class="w60 fr">
              <!-- TODO 上传资质 -->
              <SmallUploadImg ref="smallUploadImgQulafication" :maxLength="15"></SmallUploadImg>
            </div>
          </li>
          <!-- 备注-->
          <li v-if="apply_notes.display==1" class="clearfix liArea">
            <label>
              <b v-if="apply_notes.must==1" class="colorRed">*</b>
              {{apply_notes.name}}
            </label>
            <div class="w60 textarea-wx-box fr">
              <textarea
                :placeholder="other_config.dls_statement"
                v-model="apply_notes.value"
                class="textw"
                maxlength="225"
                @blur="blurEvent()"
                v-show="showTextarea"
              ></textarea>

              <div v-show="!showTextarea" @click="textareaFocus" class="textarea-cover" :class="apply_notes.value?'hasTxt':''">{{apply_notes.value?apply_notes.value:other_config.dls_statement}}</div>
            </div>

          </li>
        </ul>
        <section v-if="dls.checked">
          <section v-if="(other_config.needApplyAgreement == 1 && dls.agreement)|| (dls.img!=0)">
            <div class="agreenment">
              <van-checkbox v-model="agree" shape="square" checked-color="#FE1B49" icon-size="16px">
                我已阅读并同意
                <span
                  v-show="other_config.needApplyAgreement == 1 && dls.agreement"
                  class="J-showAgreement-title red"
                  @click="showAgreement"
                >《{{ dls.ftitle_agencies }}申请协议》</span>
                <!-- TODO 下载文档 -->
                <a v-show="dls.img!=0" @click="downloadDoc(dls.img)" download="代理商合同" class="j-download">
                  <span class="red">《代理商合同》</span>
                </a>
              </van-checkbox>
            </div>
          </section>
        </section>
        <section v-if="dhs.checked">
          <section v-if="(other_config.needApplyAgreement == 1 && dhs.agreement)|| (dhs.img!=0)">
            <div class="agreenment">
              <van-checkbox v-model="agree" shape="square" checked-color="#FE1B49" icon-size="16px">
                我已阅读并同意
                <span
                  v-if="other_config.needApplyAgreement == 1 && dhs.agreement"
                  class="J-showAgreement3-title red"
                  @click="showAgreement"
                >《{{ dhs.ftitle_agencies }}申请协议》</span>
                <!-- TODO 下载文档 -->
                <a v-if="dhs.img!=0" @click="downloadDoc(dhs.img)" download="订货商合同" class="j-download">
                  <span class="red">《订货商合同》</span>
                </a>
              </van-checkbox>
            </div>
          </section>
        </section>
        <div
          v-show="dls.checked && agree && other_config.needApplyAgreement ==1 && dls.agreement"
          class="apply_agreement apply_agreement_dls"
          style="display:block"
        >
          <section class="txt">
            <editor  :itemData="this.dls.agreement"></editor>
          </section>

        </div>
        <div
          v-show="dhs.checked && agree && other_config.needApplyAgreement ==1 && dhs.agreement"
          class="apply_agreement apply_agreement_dhs"
          style="display:block"
        >
          <section class="txt">
            <editor  :itemData="this.dhs.agreement"></editor>
          </section>
        </div>
        <section class="mlogin_but">
          <a href="javascript:;" class="J-addApply" @click="onSubmit()">{{agreeBtnText}}</a>
        </section>
      </div>
    </div>

    <map-area :visible.sync="showAreaPop" @onSelect="handleConfirm"></map-area>
    <share-btn v-if="application_poster_switch" type="2"></share-btn>
    <van-popup v-model="showDlsPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="dlsColumns"
        @cancel="showDlsPicker = false"
        @confirm="onConfirmDls"
      />
    </van-popup>
    <van-popup v-model="showDhsPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="dhsColumns"
        @cancel="showDhsPicker = false"
        @confirm="onConfirmDhs"
      />
    </van-popup>
    <!-- 授权弹出框 -->
    <small-login ref="smalllogin"></small-login>
  </main>
</template>

<script>
/*
 * @Author: cd@360shop.cn
 * @Date: 2019-09-26 16:48:09
 * @Last Modified by: zhangmeng
 * @Last Modified time: 2020-08-17 13:53:07
 */
import mapArea from '@/components/mapArea'
import { uploadImgs } from '@/api/community/article'
import SmallUploadImg from '@/components/SmallUploadImg'
import SmallAreaPicker from '@/components/smallAreaPicker/smallareapicker.vue'
import SmallLogin from '@/components/SmallLogin/smallLogin'
import editor from './editor'
import shareBtn from '../../component/shareBtn'
import small from '@/smallapp/small'
import {
  dlsdhsRequest,
  doDlsApply,
  doCheckCard
} from '@/api/identityApplication/identityApplication'
import { validateMobile, validLength } from '@/utils/validate'
import { base64_encode } from '@/utils/index'
import { postMsgVerify, getVerify } from '@/api/loginRegister/index'
import { openPage } from '@/utils/utils'
import { mpShare } from '@/utils/utils'

import Vue from 'vue'
import { RadioGroup, Radio, Checkbox, Picker, Popup } from 'vant'
Vue.use(RadioGroup)
Vue.use(Radio)
Vue.use(Checkbox)
Vue.use(Picker)
Vue.use(Popup)

export default Vue.extend({
  name: 'common',
  components: {
    mapArea,
    SmallUploadImg,
    SmallAreaPicker,
    SmallLogin,
    editor,
    shareBtn
  },
  data() {
    return {
      showDhsPicker: false,
      showDlsPicker: false,
      showDhsName: '',
      showDlsName: '',
      dlsColumns: [],
      dhsColumns: [],
      fileList: [], // 营业执照图片数组
      fileListImg: [], // 营业执照图片数组
      fileListApply: [], // 资质图片数组
      fileListImgApply: [], // 资质图片数组
      is_mmxx: false,
      areaBtnText: '请选择', // 默认文字
      showAreaPop: false,
      formData: {}, // 默认为空
      agreementValue: '', // 同意协议是否勾选 默认不勾选
      // 大部分申请条件
      // 公司名称
      company_name: {},
      apply_user_id: '', // 定制：上级ID
      // 营业执照号
      business_licence_num: {},
      // 上传营业执照
      business_licence_img: {},
      // 身份证号
      card_num: {},
      // 上传身份证
      card_img: {},
      // 性别
      sex: {},
      // 申请人
      agent_name: {},
      // 手机号码
      apply_mobile: {},
      // 微信号
      apply_weixin: {},
      // 地址信息
      apply_address: {},
      // 详细地址
      address: {},
      // 备注
      apply_notes: {},
      // 代理商信息
      dls: {},
      // 订货商信息
      dhs: {},
      // 代理商选择
      dls_level: [],
      // 订货商选择
      dhs_level: [],
      // 地址
      apply_qualifications: {}, // 上传资质
      other_config: {
        // 短信验证
        canSendMsg: '', // 默认为true
        sendMsgBtnTxt: '',
        sendMsgTime: '',
        topRequsetBg: '', // 头部图片壁纸
        apply_tip_title: '', // 欢迎语
        // 选择订货商或者代理商
        dlsRank: '', // 选中dls 默认为空
        dhsRank: '', // 选中dhs 默认为空
        applyLevel: '', // 选择代理商或者订货商 1代理商 2订货商,
        // 企业相关
        need_apply_type: '', // 是否开启选择企业或个人功能
        applyType: '', // 选中企业或者个人 默认 1
        // 地址选择列表数据
        areaCode: [], // 选择地址参数 默认为空
        needApplyAgreement: '', // 同意协议是否必须
        check_apply_mobile: '0'
      },
      verifyImg: '', // 图形验证码
      apply_level: '1',
      agree: true,
      business_licence_txt: '',
      card_txt: '',
      showTextarea: false,
      company_head: {}, // 浙江集乘网络  定制 抬头
      company_taxNumber: {}, // 浙江集乘网络  定制 税号
      dhsRank: '',
      apply_head_title: '',
      application_poster_switch: 0
      // other_config: ''
    }
  },
  methods: {
    onConfirmDhs(val, idx) {
      this.showDhsName = val
      this.other_config.dhsRank = this.dhs_level[idx].key
      this.showDhsPicker = false
      const pid = small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'
      // TODO 小程序分享
      this.shareInfo = {
        title: this.apply_head_title,
        // imageUrl: this.other_config.shopInfo.avatar,
        shareParam: this.other_config.dhsRank ?  `pid=${pid}&dhsRank=${this.other_config.dhsRank}` : `pid=${pid}`
      }
      mpShare (true, true, '/user/pages/dlsdhsApplication/index', this.shareInfo, '/dlsdhs-application')
    },

    onConfirmDls(val, idx) {
      this.showDlsName = val
      this.other_config.dlsRank = this.dls_level[idx].key
      this.showDlsPicker = false
    },

    // ios手机端失去焦点时复原页面
    blurEvent() {
      if (this.isIos) {
        const scrollHeight =
          document.documentElement.scrollTop || document.body.scrollTop || 0
        window.scrollTo(0, scrollHeight + 1)
      }
      //小程序textarea失去焦点
      this.showTextarea=false
    },
    focusEvent() {
      if (!this.apply_mobile.code) {
        this.refreshVerify()
      }
    },
    //小程序textarea获得焦点
    textareaFocus(){
      this.showTextarea=true
      const textareaObj=document.querySelector('.textarea-wx-box textarea')
      textareaObj.focus()
    },
    dlsdhsRequestFun() {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      const params = {}
      if (this.$route.query.dhsRank) {
        this.dhsRank = this.$route.query.dhsRank
        params.dhsRank = this.$route.query.dhsRank
      }
      dlsdhsRequest(params).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          // const obj = { key: 0, name: '请选择' }
          this.agent_name = res.data.agent_name
          this.apply_address = res.data.apply_address
          this.apply_mobile = res.data.apply_mobile
          this.apply_notes = res.data.apply_notes
          this.apply_weixin = res.data.apply_weixin
          this.business_licence_img = res.data.business_licence_img
          this.business_licence_num = res.data.business_licence_num
          this.card_img = res.data.card_img
          this.card_num = res.data.card_num
          this.company_name = res.data.company_name
          this.dhs = res.data.dhs
          this.dhs_level = res.data.dhs_level
          this.application_poster_switch = res.data.application_poster_switch
          // this.dhs_level.unshift(obj)
          this.dls = res.data.dls
          this.dls_level = res.data.dls_level
          // this.dls_level.unshift(obj)

          const dlsLevelList = []
          this.dls_level.map(item => {
            dlsLevelList.push(item.name)
          })
          this.dlsColumns = dlsLevelList

          const dhsLevelList = []
          this.dhs_level.map(item => {
            dhsLevelList.push(item.name)
          })

          this.dhsColumns = dhsLevelList
          this.sex = res.data.sex
          this.apply_qualifications = res.data.apply_qualifications
          this.other_config = res.data.other_config
          this.other_config.applyLevel = res.data.other_config.applyLevel + ''
          this.other_config.applyType = res.data.other_config.applyType + ''
          if (res.data.dhs.checked == 1) {
            this.apply_level = '2'
          }
          if (res.data.other_config.apply_head_title) {
            wx.setNavigationBarTitle({
              title: res.data.other_config.apply_head_title
            })
          }
          this.apply_head_title = res.data.other_config.apply_head_title
          // 处理当只有一个订货商级别的时候默认选中
          if (res.data.dhs_level.length == 1) {
            this.showDhsName = res.data.dhs_level[0].name
            this.other_config.dhsRank = res.data.dhs_level[0].key
          }
          // 处理当只有一个代理商级别的时候默认选中
          if (res.data.dls_level.length == 1) {
            this.showDlsName = res.data.dls_level[0].name
            this.other_config.dlsRank = res.data.dls_level[0].key
          }
          //  浙江集乘网络  定制 start
          if (res.data.ltd && res.data.tax) {
            this.company_head = res.data.ltd
            this.company_taxNumber = res.data.tax
          }
          // TODO 小程序分享
          const pid = small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'
          this.shareInfo = {
            title: this.apply_head_title,
            // imageUrl: this.other_config.shopInfo.avatar,
            shareParam: this.other_config.dhsRank ?  `pid=${pid}&dhsRank=${this.other_config.dhsRank}` : `pid=${pid}`
          }
          // console.log('this.shareInfo分享', this.shareInfo, this.dhsRank)
          // console.log('this.$route.query.dhsRank', this.$route.query)
          mpShare (true, true, '/user/pages/dlsdhsApplication/index', this.shareInfo, '/dlsdhs-application')
          setTimeout(() => {
            this.refreshVerify()
          }, 1000)
        } else {
          this.$Error(res.msg)
          // TODO 返回字段修改
          if (res.data.redirect_url) {
            setTimeout(() => {
              openPage(res.data.redirect_url)
            }, 1000)
          }
        }
      })
    },
    /**
     * 上传营业执照
     */
    uploadBusinessLicence(file) {
      this.uploadImgsFn(file, 'businessLicence')
    },
    /**
     * 上传资质
     */
    uploadApplyQulafication(file) {
      this.uploadImgsFn(file, 'applyQulafication')
    },
    /**
     * 删除营业执照
     */
    deleteEvent() {
      this.fileListImg = this.fileList
    },
    /**
     * 删除资质
     */
    deleteEventApply() {
      this.fileListImgApply = this.fileListApply
    },
    /**
     * 上传身份证正面
     */
    uploadCardPositive(file) {
      this.uploadImgsFn(file, 'card')
    },
    /**
     * 上传图片
     */
    uploadImgsFn(file, type) {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      const form = new FormData()
      form.append('file', file.file)
      uploadImgs(form).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          if (type == 'businessLicence') {
            this.fileList = []
            const obj = {
              url: res.data.pic_url
            }
            this.fileListImg.push(obj)
            this.fileList = this.fileListImg
          } else if (type == 'card') {
            this.card_img.value = res.data.pic_url
            this.card_txt = '上传成功'
          } else if (type == 'applyQulafication') {
            this.fileListApply = []
            const obj = {
              url: res.data.pic_url
            }
            this.fileListImgApply.push(obj)
            this.fileListApply = this.fileListImgApply
          }
        } else {
          if (type == 'businessLicence') {
            this.business_licence_txt = '上传失败'
          } else if (type == 'card') {
            this.card_img.value = ''
            this.card_txt = '上传失败'
          }
        }
      })
    },
    // TODO 验证码
    // 刷新验证码
    refreshVerify() {
      getVerify().then((res) => {
        const src = `data:image/jpg;base64,${base64_encode(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`
        this.verifyImg = src
      })
    },

    // 获取验证码倒计时
    setTimeoutVerify() {
      let count = 60
      this.other_config.sendMsgBtnTxt = count + '秒后重新获取'
      const timer = setInterval(() => {
        this.other_config.sendMsgBtnTxt = count + '秒后重新获取'
        if (count <= 0) {
          this.other_config.sendMsgBtnTxt = '发送验证码'
          clearInterval(timer)
        }
        count--
      }, 1000)
    },
    // 获取短信验证码
    refreshmsgVerify() {
      if (this.other_config.sendMsgBtnTxt == '发送验证码') {
        const mobile = this.apply_mobile.value || ''
        const code = this.apply_mobile.code || ''
        if (validateMobile(mobile)) {
          if (validLength(code)) {
            const data = { mobile, code }
            postMsgVerify(data).then(res => {
              this.setTimeoutVerify()
              if (res.status === 1) {
                // console.log(res)
              } else {
                this.$Error(res.msg)
              }
            })
          } else {
            this.$Error('请输入验证码')
            return false
          }
        } else {
          this.$Error('请输入正确的手机号码')
          return false
        }
      }
    },
    // 切换代理商订货商
    selectApplyLevel(value) {
      if (value === 1) {
        this.dls.checked = true
        this.dhs.checked = false
      }
      if (value === 2) {
        this.dhs.checked = true
        this.dls.checked = false
      }
    },
    // 小程序选择省市区
    procityareaInfo(val) {
      this.handleConfirm(val)
    },

    // 点击调用地址选择
    selectAddress() {
      this.showAreaPop = true
    },
    // 确认
    handleConfirm(val) {
      if (!val.province_id || !val.city_id) {
        this.$Error('请选择完整的省市县')
      } else {
        this.showAreaPop = false
        this.areaBtnText = val.province_name + ' ' + val.city_name + ' ' + val.area_name
        this.formData.province_id = val.province_id
        this.formData.city_id = val.city_id
        this.formData.area_id = val.area_id
      }
    },
    showAgreement() {
      this.agree = !this.agree
    },
    //TODO 下载合同待处理——张猛
    downloadDoc(url){
        wx.downloadFile({
          url: url,
          success: function (res) {
            let fileType = url.substring(url.lastIndexOf(".")+1);
            if(fileType.indexOf('@') !== -1) {
              fileType = fileType.substring(0, fileType.indexOf('@'));
            }
            const tempPath = res.tempFilePath;
            const imgType = "|png|gif|jpg|jpeg|";
            if(imgType.indexOf(fileType)>0) {
              wx.saveImageToPhotosAlbum({
                filePath: tempPath,
                success(res) {
                  // console.log('保存成功');
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                },
                fail: function(err) {
                  if(err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                    wx.showModal({
                      title: '提示',
                      content: '需要您授权保存相册',
                      showCancel: false,
                      success: modalSuccess => {
                        wx.openSetting({
                          success(settingdata) {
                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                              // console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                            }else {
                              // console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                            }
                          }
                        })
                      }
                    })
                  }
                }
              })
            } else {
              wx.saveFile({
                tempFilePath: tempPath,
                success:function(res){
                  const savePath = res.savedFilePath;
                  wx.openDocument({
                    filePath: savePath,
                    fileType: fileType,
                    showMenu: true,
                    success :function(res){
                      // console.log('打开文档成功')
                    },
                  });
                },
                fail: function (err) {
                  // console.log('保存失败：', err)
                }
              })
            }
          }
        })

    },
    // 同意协议/验证数据
    onSubmit() {
      // TODO 上传
      // 营业执照数组
      let business_licence_img_arr=[]
        business_licence_img_arr=this.$refs.smallUploadImgYYZZ?this.$refs.smallUploadImgYYZZ.imgList:[]

      // 资质数组
      let apply_qualifications=[]
        apply_qualifications=this.$refs.smallUploadImgQulafication?this.$refs.smallUploadImgQulafication.imgList:[]


      //身份证
        this.card_img.value=this.$refs.smallUploadImgCardPos?this.$refs.smallUploadImgCardPos.imgList[0]:''


      const data = {
        apply_level: this.apply_level,
        dls_rank: this.other_config.dlsRank,
        dhs_rank: this.other_config.dhsRank,
        apply_type:
          this.other_config.need_apply_type == 0
            ? ''
            : this.other_config.applyType,
        company_name: this.company_name.value,
        business_licence_num: this.business_licence_num.value,
        business_licence_img: business_licence_img_arr.join(','),
        apply_qualifications: apply_qualifications.join(','),
        card_num: this.card_num.value,
        card_img: this.card_img.value,
        sex: this.sex.value,
        agent_name: this.agent_name.value,
        mobile: this.apply_mobile.value,
        weixin_account: this.apply_weixin.value,
        code: this.apply_mobile.code || '',
        vcode: this.apply_mobile.vcode || '',
        province_id: this.formData.province_id,
        city_id: this.formData.city_id,
        area_id: this.formData.area_id,
        address: this.address.value || '',
        apply_notes: this.apply_notes.value,
        user_id: this.$route.query.pid,
        apply_user_id: this.apply_user_id
      }
      // 浙江集乘网络  定制 start
      if (this.company_head.name) {
        data.ltd = this.company_head.value
      }
      if (this.company_taxNumber.name) {
        data.tax = this.company_taxNumber.value
      }
      // 浙江集乘网络  定制 end
      if (data.apply_level == 1) {
        if (!data.dls_rank) {
          this.$Error('请选择' + this.dls.ftitle_agencies + '级别')
          return false
        }
      } else if (data.apply_level == 1) {
        if (!data.dhs_rank) {
          this.$Error('请选择' + this.dhs.ftitle_agencies + '级别')
          return false
        }
      }
      // 浙江集乘网络  定制 start
      if (this.company_head.must == 1) {
        if (!this.company_head.value) {
          this.$Error('公司抬头不能为空')
          return false
        }
      }
      if (this.company_taxNumber.must == 1) {
        if (!this.company_taxNumber.value) {
          this.$Error('税号不能为空')
          return false
        }
      }
      // 浙江集乘网络  定制 end
      if (!data.apply_level) {
        this.$Error('请选择加盟方式')
        return false
      }
      if (this.other_config.need_apply_type == 1) {
        // 公司名称
        if (
          this.company_name.display == 1 &&
          this.company_name.must == 1 &&
          data.apply_type == 2
        ) {
          if (!data.company_name) {
            this.$Error(this.company_name.name + '不能为空')
            return false
          }
        }
        // 营业执照号
        if (
          this.business_licence_num.display == 1 &&
          this.business_licence_num.must == 1 &&
          data.apply_type == 2
        ) {
          if (!data.business_licence_num) {
            this.$Error(this.business_licence_num.name + '不能为空')
            return false
          }
        }
        // 营业执照号图片
        if (
          this.business_licence_img.display == 1 &&
          this.business_licence_img.must == 1 &&
          data.apply_type == 2
        ) {
          if (!data.business_licence_img) {
            this.$Error(this.business_licence_img.name + '不能为空')
            return false
          }
        }
        // 身份证号
        if (this.card_num.display == 1 && this.card_num.must == 1) {
          if (!data.card_num) {
            this.$Error(this.card_num.name + '不能为空')
            return false
          }
          const reg_card = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/gi
          if (!reg_card.test(data.card_num)) {
            this.$Error(this.card_num.name + '有误,请检查后提交')
            return false
          }
        }
        // 身份证图片
        if (this.card_img.display == 1 && this.card_img.must == 1) {
          if (!data.card_img) {
            this.$Error(this.card_img.name + '不能为空')
            return false
          }
        }
        // 性别
        if (this.sex.display == 1 && this.sex.must == 1) {
          if (!data.sex) {
            this.$Error('请选择' + this.sex.name)
            return false
          }
        }
      }
      // 申请人
      if (this.agent_name.display == 1 && this.agent_name.must == 1) {
        if (!data.agent_name) {
          this.$Error(this.agent_name.name + '不能为空')
          return false
        }
      }
      // 联系人电话
      if (this.apply_mobile.display == 1 && this.apply_mobile.must == 1) {
        if (!data.mobile) {
          this.$Error(this.apply_mobile.name + '不能为空')
          return false
        }
        const reg_card = /^1[3456789]\d{9}$/gi
        if (!reg_card.test(data.mobile)) {
          this.$Error(this.apply_mobile.name + '有误,请检查后提交')
          return false
        }
      }
      // 微信号
      if (this.apply_weixin.display == 1 && this.apply_weixin.must == 1) {
        if (!data.weixin_account) {
          this.$Error(this.apply_weixin.name + '不能为空')
          return false
        }
      }
      // 短信验证码
      if (
        this.apply_mobile.display == 1 &&
        this.other_config.check_apply_mobile == 1
      ) {
        if (!data.vcode) {
          this.$Error('短信验证码不能为空')
          return false
        }
      }
      // 地址信息
      if (this.apply_address.display == 1 && this.apply_address.must == 1) {
        if (!data.province_id) {
          this.$Error(this.apply_address.name + '不能为空')
          return false
        }
        if (!data.address) {
          this.$Error('详细地址不能为空')
          return false
        }
      }
      // 上传资质
      if (this.apply_qualifications.display == 1 && this.apply_qualifications.must == 1) {
        if (!data.apply_qualifications) {
          this.$Error(this.apply_qualifications.name + '不能为空')
          return false
        }
      }
      // 备注
      if (this.apply_notes.display == 1 && this.apply_notes.must == 1) {
        if (!data.apply_notes) {
          this.$Error(this.apply_notes.name + '不能为空')
          return false
        }
      }
      // 协议
      if (!this.agree) {
        this.$Error('请接受申请协议')
        return false
      }
      // 验证身份证号唯一性
      if (
        this.card_num.display == 1 &&
        this.card_num.must == 1 &&
        this.other_config.need_apply_type == 1
      ) {
        this._checkCardSole(data)
      } else {
        this._doStoreApply(data)
      }
    },
    // 验证身份证号唯一性
    _checkCardSole(data) {
      const IDCard = {
        card_num: data.card_num,
        type: data.apply_level
      }
      doCheckCard(IDCard).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this._doStoreApply(data)
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 提交
    _doStoreApply(data) {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      doDlsApply(data).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.$Error('申请成功')
          setTimeout(() => {
            // window.location.href = res.jump_url
            openPage(res.jump_url)
          }, 1000)
        } else {
          this.$Error(res.msg)
        }
      })
    }
  },
  created() {
    this.dlsdhsRequestFun()
    // this.refreshVerify()
    const is_mmxx = this.$_shop('$_mmxx', this.$route.query.sid)
    this.is_mmxx = is_mmxx
  },
  mounted() {
    if (!small.checkLogin()) {
      this.$refs.smalllogin.openSmallLoginPop()
    }
    window.$$subscribe('loginReload', reload => {
      if (reload) {
        this.dlsdhsRequestFun()
        // this.refreshVerify()
      }
    })
  },
  computed: {
    agreeBtnText() {
      if (this.dls.checked) {
        if (
          (this.other_config.needApplyAgreement == 1 && this.dls.agreement) ||
          this.dls.img
        ) {
          return '同意协议并申请'
        } else {
          return '确定'
        }
      } else if (this.dhs.checked) {
        if (
          (this.other_config.needApplyAgreement == 1 && this.dhs.agreement) ||
          this.dhs.img
        ) {
          return '同意协议并申请'
        } else {
          return '确定'
        }
      }
    }
  }
})
</script>
<style lang="scss">
.apply_agreement {
    .txt {
      img {
        max-width: 100% !important;
      }
    }
  }
  .van-checkbox__label {
    color: #666;
  }
  .van-radio__label {
    font-weight: 500;
  }
  .van-radio-group {
    display: inline-block;
  }
  .van-radio__icon--checked .van-icon,.van-checkbox__icon--checked .van-icon {
    background-color: #FE1B49;
    border-color: #FE1B49;
  }

</style>
<style lang="scss">
@import 'src/styles/identityApplication/index.scss';
.apply-dls-wrapper {
    width: 100%;
  .apply_headimg {
      position: relative;
      width: 100%;
      height: 250px;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .reference {
        position: absolute;
        top: 20px;
        left: 20px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50px;
        padding-right: 20px;
        display: flex;
        align-items: center;
        color: #fff;
        max-width: 95%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        img {
          width: 70px;
          height: 70px;
          object-fit: cover;
          border-radius: 50px;
          margin-right: 20px;
        }
      }
    }
  .apply_wrapper {
      width: calc(100% - 50px);
      height: 100%;
      margin: 0 25px;
      padding: 0 25px;
      box-sizing: border-box;
      border-radius: 20px;
      background-color: #fff;
      overflow: hidden;

    .autoHeight{
      height: auto!important;
      .van-uploader{
        display: block!important;
        margin-top: 10px;
      }
    }
    .agreenment {
      .red {
        color: #FE1B49;
        // margin-right: 10px;
      }
    }
    .txt {
      overflow-x: auto;
    }
  }
  .area-picker{
    padding:32px 30px;
    color:#666;
  }
  .verify-img {
    height: 70px;
    position: absolute;
    right: 0px;
    display: inline-block;
    margin-top: 5px;
    width: 32%;
  }
}
</style>
